package com.wsx.ones.boots.grpc;

import com.wsx.ones.boots.service.WebServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;

/**
 * @author wangshuaixin
 * @Title: com.wsx.ones.boots.grpc.WebGrpcServer
 * @Description: TODO
 * @date 2019/05/20
 */
public class WebGrpcServer {

    private Server server;
    private int port = 8871;

    //服务的启动
    public  void start() {
        server = simple(port);
    }

    public  void start(int port) {
        server = simple(port);
    }

    //简单的服务启动操作
    private Server simple(int port) {
        Server grpcServer = null;
        try {
            grpcServer = ServerBuilder.forPort(port)
                    .addService(new WebServiceImpl())
                    .build()
                    .start();

            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    WebGrpcServer.this.server.shutdown();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return grpcServer;
    }

    private Server netty(int port) {
        Server grpcServer = null;
        try {
            grpcServer = NettyServerBuilder.forPort(port)
                    .addService(new WebServiceImpl())
                    .build()
                    .start();

            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    WebGrpcServer.this.server.shutdown();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return grpcServer;
    }
}
